<template>
  <div class="main_margin">
    <el-row>
      <el-col :span="4">
        <div class="left_tree warpper">
          <el-tree
            id="tree"
            ref="tree"
            :data="manager_data"
            :props="defaultProps"
            highlight-current
            @node-click="handleNodeClick"
            node-key="RUID"
            :current-node-key="currentNodeKey"
            :default-expanded-keys="sider_default_list"
            @node-expand="handleNodeExpand"
            @node-collapse="handleNodeCollapse"
          >
            <span class="span-ellipsis" slot-scope="{ node }">
              <span :title="node.label">{{ node.label }}</span>
            </span>
          </el-tree>
        </div>
      </el-col>
      <el-col :span="1">
        <div style="border: #fff 1px solid"></div>
      </el-col>
      <el-col :span="18">
        <el-row class="btn_row" style="margin-top: 20px">
          <el-col :span="16">
            <div style="border: #fff 1px solid"></div>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click="showinsertCategory()" style=""
              >新增</el-button
            >
          </el-col>
          <el-col :span="2">
            <el-button
              type="primary"
              @click="batchDel()"
              >批量删除</el-button
            >
          </el-col>
        </el-row>
        <el-table
          :data="tableData"
          border
          style="width: 100%"
          ref="multipleTable"
          :row-style="{height:'30px'}"
          :header-cell-style="{}"
        >
          <el-table-column type="selection" width="100"> </el-table-column>
          <el-table-column prop="name" label="权限名称" width="200">
          </el-table-column>
          <el-table-column prop="orderno" label="顺序号" width="200">
            <!-- :formatter="stateFormatType" -->
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                size="small"
                @click="showupdateCategory(scope.$index, scope.row)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                size="small"
                @click="delClick(scope.index, scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="2"></el-col>
    </el-row>

    <!-- 权限设置 -->
    <el-dialog
      title="权限设置"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item
          label="上级权限"
          :label-width="formLabelWidth"
          prop="parentid"
        >
          <SelectTree
            :props="props"
            :options="optionData"
            :value="form.parentid"
            :clearable="isClearable"
            :accordion="isAccordion"
            @getValue="getValue($event)"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item
          label="权限名称"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="显示顺序"
          :label-width="formLabelWidth"
          prop="orderno"
        >
          <el-input
            v-model.number="form.orderno"
            type="text"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="描述"
          :label-width="formLabelWidth"
          prop="description"
        >
          <el-input
            v-model.number="form.description"
            type="text"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelUpdateCategory">取 消</el-button>
        <el-button type="primary" @click="sureCategory">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 权限设置 -->

    <!-- 删除 -->
    <el-dialog
      title="信息"
      :visible.sync="deleteVisible"
      width="30%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <span>确认是否删除当前分类？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="delCancel()">取 消</el-button>
        <el-button type="primary" @click="delMenu">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 删除 -->
  </div>
</template>
<script>
import SelectTree from "../../components/treeSelect";
import CheckSelectTree from "../../components/CheckTreeSelect";
import { menulist, saveObject, saveObjects } from "../../api/admin";
export default {
  name: "manager",
  data() {
    return {
      currentNodeKey: "", //初始化默认选中节点
      treechecktable: "",
      defaultShowNodes: [],
      formLabelWidth: "120px",
      insorup: false, //判断是新增还是修改(true为新增,false为修改)
      isClearable: true, // 可清空（可选）
      isAccordion: true, // 可收起（可选）
      props: {
        // 配置项（必选）
        value: "RUID",
        label: "name",
        children: "children",
      },
      manager_data: [], //树状图菜单
      form: {
        parentid: "",
        RUID: "", //在此页面用来获取上级RUID
        name: "",
        orderno: "",
        description:"",
      },
      tableData: [], //右侧table数组
      dialogFormVisible: false, //编辑|新增 模态框
      deleteVisible: false,
      del_row: {}, //删除项数据
      defaultProps: {
        //树状图默认样式
        children: "children",
        label: "name",
      },
      sider_default_list: [], //树状图默认打开节点
      rules: {
        name: [
          {
            required: true,
            message: "请输入菜单名称",
            trigger: "blur",
          },
        ],
        orderno: [
          {
            required: true,
            message: "请输入显示顺序",
            trigger: "blur",
          },
          {
            type: "number",
            message: "请输入数字",
            trigger: "blur",
          },
        ],
        parentid: [
          {
            required: true,
            message: "请选择上级分类",
            trigger: "change",
          },
        ],
      },
    };
  },
  components: {
    SelectTree,
    CheckSelectTree,
  },
  computed: {
    /* 转树形数据 */
    optionData() {
      let cloneData = JSON.parse(JSON.stringify(this.manager_data)); // 对源数据深度克隆
      return cloneData;
    },
  },
  methods: {
    handleNodeExpand(data) {
      // 保存当前展开的节点
      let flag = false;
      this.defaultShowNodes.some((item) => {
        if (item === data.RUID) {
          // 判断当前节点是否存在， 存在不做处理
          flag = true;
          return true;
        }
      });
      if (!flag) {
        // 不存在则存到数组里
        this.defaultShowNodes.push(data.RUID);
      }
    },
    // 树节点关闭
    handleNodeCollapse(data) {
      this.defaultShowNodes.some((item, i) => {
        if (item === data.RUID) {
          // 删除关闭节点
          this.defaultShowNodes.length = i;
        }
      });
      this.$nextTick(() => {
        for (
          let i = 0;
          i < this.$refs.tree.store.getNode(data.RUID).data.children.length;
          i++
        ) {
          this.$refs.tree.store.getNode(data.RUID).childNodes[
            i
          ].expanded = false;
        }
      });
    },
    getMenuList() {
      menulist({
        type: "permission6",
        rootnode: {
          RUID: "permission",
          exist: "1",
          show: "1",
        },
        deep: -1,
        field: "RUID,`name`,parentid,orderno,description",
        key: {
          RUID: "RUID",
          name: "name",
          children: "children",
        },
        filter: [],
        order: [
          {
            fieldname: "name",
            type: "D",
          },
        ],
      }).then((res) => {
        if (res.cxajaxrc == "0") {
            console.log(res);
          this.manager_data = res.nodes;
          this.sider_default_list.push(res.nodes[0].RUID); //设置左侧Sider默认选中打开
          this.currentNodeKey = res.nodes[0].RUID;
          this.$nextTick(() => {
            this.$refs.tree.setCurrentKey(this.currentNodeKey); //数据请求成功后，设置默认current
          });
          if (this.defaultShowNodes != [] && this.defaultShowNodes.length > 0) {
            this.sider_default_list = this.defaultShowNodes;
          }
          console.log(typeof this.tableData);
          if (this.tableData == [] || typeof this.tableData == "object") {
            this.tableData = res.nodes[0].children;
          }
          if (this.treechecktable != "") {
            this.tableData = [];
            this.gettabelcolumnbyid(res.nodes, this.treechecktable);
          }
        } else {
          this.$message.error("菜单列表:检索资料时发生错误");
        }
      });
    },
    getpermissionData() {
      menulist({
        type: "permission6",
        rootnode: {
          RUID: "permission",
          exist: "0",
          show: "0",
        },
        deep: -1,
        field: "RUID,`name`,parentid",
        key: {
          RUID: "RUID",
          name: "name",
          children: "children",
        },
        filter: [],
        order: [
          {
            fieldname: "name",
            type: "D",
          },
        ],
      }).then((res) => {
        if (res.cxajaxrc == "0") {
          this.permissionData = res.nodes;
          for (let i = 0; i < this.form.permission.length; i++) {
            this.getnamebyid(this.permissionData, this.form.permission[i]);
          }
        } else {
          this.$message.error("菜单列表:检索资料时发生错误");
        }
      });
    },
    gettabelcolumnbyid(data, id) {
      for (let j = 0; j < data.length; j++) {
        if (id == data[j].RUID) {
          this.tableData = data[j].children;
        }
        if (data[j].children) {
          this.gettabelcolumnbyid(data[j].children, id);
        }
      }
    },
    getValue(value) {
      //下拉树状图获取选中值
      this.form.parentid = value;
    },
    getCheckValue(value) {
      this.form.permission = value;
    },
    handleNodeClick(data) {
      this.treechecktable = data.RUID; //每次切换时保存当前选中的节点,新增修改删除后table不变
      this.tableData = [];
      this.tableData = data.children;
      // this.$refs.tree.$children[0].$children[0].$el.style.backgroundColor='rgb(255, 235, 192)';
    },
    showinsertCategory() {
      //点击新增事件
      console.log(this.manager_data[0].RUID);
      this.form.parentid = this.manager_data[0].RUID;//默认给上级权限赋初始值
      this.dialogFormVisible = true;
      this.insorup = true;
    },
    insertCategory() {
      //新增路由
      this.$refs["form"].validate((valid) => {
        if (valid) {
          saveObject({
            type: "permission6",
            codeflag: "1",
            object: {
              parentid: this.form.parentid,
              name: this.form.name,
              orderno: this.form.orderno,
              description: this.form.description,
            },
          }).then((res) => {
            if (res.cxajaxrc == "0") {
              this.$message.success("新增成功!");
              this.getMenuList();
              this.dialogFormVisible = false;
            } else {
              this.$message.error("新增错误!!");
            }
          });
        } else {
          this.$message.error("请输入完整!!");
          return false;
        }
      });
    },
    updateCategory() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          saveObject({
            type: "permission6",
            codeflag: "1",
            object: {
              RUID: this.form.RUID,
              parentid: this.form.parentid,
              name: this.form.name,
              orderno: this.form.orderno,
              description: this.form.description,
            },
          }).then((res) => {
            if (res.cxajaxrc == "0") {
              this.$message.success("修改成功!");
              this.$refs["form"].resetFields();
              this.getMenuList();
              this.dialogFormVisible = false;
            } else {
              this.$message.error("修改错误!!");
            }
          });
        } else {
          this.$message.error("请输入完整!!");
          return false;
        }
      });
    },
    batchDel(){
      let list = this.$refs.multipleTable.selection;
      if (list.length > 0) {
        var delstr = "";
        for (let i = 0; i < list.length; i++) {
          delstr=""+list[i].RUID+"";
        }
        // deleteObject({
        //   type: "permission6",
        //   codeflag: "1",
        //   RUID: delstr,
        // }).then((res) => {
        //   if (res.cxajaxrc == "0") {
        //     this.getMenuList();
        //     this.$message.success("批量显示节点成功!");
        //   } else {
        //     this.$message.error("批量显示节点错误!!");
        //   }
        // });
      } else {
        this.$message.warning("请选中要删除的行!");
      }
    },
    sureCategory() {
      if (this.insorup) {
        this.insertCategory(); //新增
      } else {
        this.updateCategory(); //修改
      }
    },
    showupdateCategory(index, row) {
        console.log(row);
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.form.RUID = row.RUID;
        this.form.parentid = row.parentid;
        this.form.name = row.name;
        this.form.orderno = row.orderno;
        this.form.description = row.description;
      });
      this.insorup = false;
    },
    stateFormatType(row, column, cellValue) {
      if (cellValue != null && cellValue != "") {
        cellValue =
          cellValue.length >= 30 ? cellValue.slice(0, 30) + "..." : cellValue;
        return cellValue;
      } else {
        return "无";
      }
    },
    delClick() {
      this.del_row = row; //要删除项的数据
      this.deleteVisible = true;
    },
    initform() {
      this.form.description = "";
    },
    cancelUpdateCategory() {
      this.initform();
      this.$refs["form"].resetFields();
      this.dialogFormVisible = false;
    },
    delMenu() {},
    delCancel() {},
  },
  beforeMount: function () {
    this.getMenuList();
  },
};
</script>
<style>
.el-table td, .el-table th{
  padding:2px 0;
}

.warpper .el-tree--highlight-current /deep/ .el-tree-node.is-checked > .el-tree-node__content {
  background-color: rgb(255, 235, 192);
  color: #333;
}
.warpper .el-tree--highlight-current /deep/ .el-tree-node.is-current > .el-tree-node__content {
  background-color: rgb(255, 235, 192);
  color: #333;
}
.el-tree /deep/ .el-tree-node .el-tree-node__content {
  margin:2px 0;
}
.el-tree /deep/ .el-tree-node__children .el-tree-node__content{
  margin:2px 0;
}

.el-tree-node__expand-icon {
  font-size: 18px;
  color: rgb(64, 158, 255);
}

.main_margin {
  background-color: #fff;
  margin: 10px;
  height: 100%;
}
.el-table{
  font-size: 13px;
  font-family: '宋体';
}

.left_tree {
  margin-top: 20px;
  margin-left: 10px;
  font-family: SimSun;
  font-size: 13px;
  text-align: left;
  border: rgb(181, 203, 236) 1px solid;
  padding: 10px;
  padding-bottom: 60px;
}

.btn_row {
  margin-bottom: 10px;
  line-height: 40px;
}

.span-ellipsis {
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.el-tree >>> .el-tree-node__label {
  font-size: 18px;
}
</style>
<style scoped>
</style>
